<template>
	<view class="comment-page">
		<!-- 顶部导航栏 -->
		<view class="navbar">
			<view class="back-btn" @click="navigateBack">
				<text class="iconfont icon-arrow-left"></text>
			</view>
			<view class="title">评价商品</view>
			<view class="empty-btn"></view>
		</view>
		
		<!-- 订单信息提示 -->
		<view class="order-info-tip" v-if="orderId">
			<text>订单号：{{ orderId }}</text>
		</view>
		
		<!-- 商品列表（根据商品数量生成评价项） -->
		<view class="goods-list">
			<view class="goods-comment-item" v-for="(goods, index) in goodsList" :key="index">
				<!-- 商品信息 -->
				<view class="goods-info">
					<image class="goods-img" :src="goods.image" mode="aspectFill"></image>
					<view class="goods-detail">
						<text class="goods-title">{{ goods.title }}</text>
						<text class="goods-attr">{{ goods.attr }}</text>
						<text class="goods-price">{{ goods.price }}</text>
					</view>
				</view>
				
				<!-- 评分区域 -->
				<view class="rating-section">
					<view class="section-title">商品评分</view>
					<view class="stars-container">
						<view 
							class="star-item" 
							v-for="(star, starIndex) in 5" 
							:key="starIndex"
							@click="selectStar(index, starIndex + 1)"
						>
							<text 
								:style="{ 
									color: starIndex < goods.selectedStar ? '#FFD700' : '#cccccc', 
									fontSize: '36px',
									transition: 'all 0.2s'
								}"
							>★</text>
						</view>
					</view>
					<view class="rating-text">{{ goods.selectedStar > 0 ? ratingTexts[goods.selectedStar - 1] : '' }}</view>
				</view>
				
				<!-- 评价内容 -->
				<view class="content-section">
					<view class="section-title">评价内容</view>
					<textarea 
						class="comment-input" 
						placeholder="请描述您对商品的体验..." 
						v-model="goods.commentContent"
						@input="checkContentLength(index)"
						maxlength="200"
					></textarea>
					<view class="word-count">{{ goods.contentLength }}/200</view>
				</view>
				
				<!-- 上传图片 -->
				<view class="image-upload-section">
					<view class="section-title">上传图片（最多9张）</view>
					<view class="image-container">
						<!-- 已上传的图片 -->
						<view 
							class="image-item" 
							v-for="(image, imgIndex) in goods.uploadedImages" 
							:key="imgIndex"
						>
							<image :src="image" mode="aspectFill"></image>
							<view class="delete-btn" @click="deleteImage(index, imgIndex)">
								<text class="iconfont icon-delete"></text>
							</view>
						</view>
						
						<!-- 添加图片按钮 -->
						<view 
							class="add-image-btn" 
							@click="chooseImage(index)"
							v-if="goods.uploadedImages.length < 9"
						>
							<text class="iconfont icon-camera"></text>
						</view>
					</view>
				</view>
				
				<!-- 匿名评价 -->
				<view class="anonymous-section">
					<view class="anonymous-label">匿名评价</view>
					<view class="switch-container">
						<switch 
							v-model="goods.isAnonymous" 
							@change="toggleAnonymous(index)"
							active-color="#FF4D4F"
						></switch>
					</view>
				</view>
				
				<!-- 分隔线 -->
				<view class="divider" v-if="index < goodsList.length - 1"></view>
			</view>
		</view>
		
		<!-- 提交按钮 -->
		<view class="submit-btn" :class="{ disabled: !canSubmit }" @click="submitComment">
			<text>提交评价</text>
		</view>
	</view>
</template>

<script>
export default {
  data() {
    return {
      orderId: '',
      spuIds: [],    // 多个spuId数组
      skuIds: [],    // 多个skuId数组
      goodsList: [], // 每个商品的评价数据
      ratingTexts: ['非常差', '差', '一般', '好', '非常好'],
      isSubmitting: false
    };
  },
  
  computed: {
    // 检查是否可以提交（所有商品必须有评分和评价内容）
    canSubmit() {
      if (this.isSubmitting || this.goodsList.length === 0) return false;
      
      return this.goodsList.every(goods => {
        return goods.selectedStar > 0 && goods.commentContent.trim().length > 0;
      });
    }
  },
  
  onLoad(options) {
    console.log('评价页面接收参数:', options);
    
    // 接收并解析参数
    this.orderId = options.orderId || '';
    this.spuIds = options.spuIds ? options.spuIds.split(',') : [];
    this.skuIds = options.skuIds ? options.skuIds.split(',') : [];
    
    // 验证参数完整性
    if (!this.orderId || this.spuIds.length === 0 || this.skuIds.length === 0) {
      uni.showModal({
        title: '提示',
        content: '订单或商品信息不完整，无法评价',
        showCancel: false,
        success: () => uni.navigateBack({ delta: 1 })
      });
      return;
    }
    
    // 加载订单商品信息并生成评价项
    this.getOrderInfoFromStorage();
  },
  
  methods: {
    // 从本地存储加载订单信息，初始化评价项
    getOrderInfoFromStorage() {
      const orderInfo = uni.getStorageSync('currentOrderInfo');
      
      if (!orderInfo || !orderInfo.goodsList || orderInfo.goodsList.length === 0) {
        uni.showModal({
          title: '提示',
          content: '订单信息不完整',
          showCancel: false,
          success: () => uni.navigateBack({ delta: 1 })
        });
        return;
      }
      
      // 根据商品数量生成评价项，绑定对应的spuId和skuId
      this.goodsList = orderInfo.goodsList.map((goods, index) => {
        return {
          image: goods.image || '',
          title: goods.title || '',
          attr: goods.attr || '',
          price: goods.price || '',
          spuId: this.spuIds[index] || '',  // 绑定当前商品的spuId
          skuId: this.skuIds[index] || '',  // 绑定当前商品的skuId
          selectedStar: 0,                  // 初始评分
          commentContent: '',               // 评价内容
          contentLength: 0,                 // 内容长度
          isAnonymous: 0,                   // 是否匿名（0-不匿名，1-匿名）
          uploadedImages: [],               // 已上传图片URL
          tempFilePaths: []                 // 临时图片路径（用于上传）
        };
      });
      
      console.log('初始化多商品评价数据:', this.goodsList);
    },
    
    // 选择评分（针对第index个商品）
    selectStar(goodsIndex, starCount) {
      this.$set(this.goodsList[goodsIndex], 'selectedStar', starCount);
    },
    
    // 计算评价内容长度
    checkContentLength(goodsIndex) {
      const content = this.goodsList[goodsIndex].commentContent || '';
      this.$set(this.goodsList[goodsIndex], 'contentLength', content.length);
    },
    
    // 选择图片
    chooseImage(goodsIndex) {
      const maxCount = 9 - this.goodsList[goodsIndex].uploadedImages.length;
      
      uni.chooseImage({
        count: maxCount,  // 最多可选择的图片数量
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 临时图片路径（用于上传）
          const tempFilePaths = res.tempFilePaths;
          // 本地预览图片URL
          const tempUrls = res.tempFilePaths;
          
          // 更新当前商品的图片数据
          this.goodsList[goodsIndex].uploadedImages = [
            ...this.goodsList[goodsIndex].uploadedImages,
            ...tempUrls
          ];
          this.goodsList[goodsIndex].tempFilePaths = [
            ...this.goodsList[goodsIndex].tempFilePaths,
            ...tempFilePaths
          ];
        }
      });
    },
    
    // 删除图片
    deleteImage(goodsIndex, imgIndex) {
      // 删除预览图
      this.goodsList[goodsIndex].uploadedImages.splice(imgIndex, 1);
      // 删除临时路径
      this.goodsList[goodsIndex].tempFilePaths.splice(imgIndex, 1);
    },
    
    // 切换匿名评价
    toggleAnonymous(goodsIndex) {
      this.$set(
        this.goodsList[goodsIndex], 
        'isAnonymous', 
        this.goodsList[goodsIndex].isAnonymous ? 0 : 1
      );
    },
    
    // 提交评价
    submitComment() {
      if (!this.canSubmit) return;
      
      this.isSubmitting = true;
      uni.showLoading({ title: '提交中...' });
      
      try {
        const token = uni.getStorageSync('token');
        const filesToUpload = [];
        const orderCommentDTOs = [];
        
        // 遍历所有商品，构建评价数据
        this.goodsList.forEach(goods => {
          // 构建评价信息（包含spuId和skuId）
          orderCommentDTOs.push({
            spuId: goods.spuId,
            skuId: goods.skuId,
            score: goods.selectedStar,
            content: goods.commentContent,
            isAnonymous: goods.isAnonymous,
			imgFilesSize: goods.tempFilePaths.length  // 新增：当前商品的图片数量
          });
          
          // 收集图片（用于上传）
          goods.tempFilePaths.forEach(filePath => {
            filesToUpload.push({
              name: 'imgFiles',
              uri: filePath,
              type: 'image/jpeg'
            });
          });
        });
        
        // 调用上传接口
        uni.uploadFile({
          url: 'http://127.0.0.1:9100/api/order/user/comment',
          files: filesToUpload,
          formData: {
            orderId: this.orderId,
            commentCount: this.goodsList.length,
            orderCommentsJson: JSON.stringify(orderCommentDTOs)
          },
          header: { 'Authorization': token },
          success: (res) => {
            const result = JSON.parse(res.data);
            if (result.code === 200) {
              uni.showToast({ title: '评价成功', icon: 'success' });
              // 延迟返回订单列表页
              setTimeout(() => {
                uni.navigateBack({ delta: 1 });
              }, 1500);
            } else {
              uni.showToast({ title: result.msg || '评价失败', icon: 'none' });
            }
          },
          fail: (err) => {
            console.error('评价提交失败:', err.msg);
			uni.showToast({
				title:err.msg
			})
            // uni.showToast({ title: '网络异常，请重试', icon: 'none' });
          },
          complete: () => {
            this.isSubmitting = false;
            uni.hideLoading();
          }
        });
      } catch (error) {
        console.error('评价提交异常:', error);
        this.isSubmitting = false;
        uni.hideLoading();
        uni.showToast({ title: '提交失败，请重试', icon: 'none' });
      }
    },
    
    // 返回上一页
    navigateBack() {
      uni.navigateBack({ delta: 1 });
    }
  }
};
</script>

<style>
/* 样式保持不变，无需修改 */
page {
	background-color: #f5f5f5;
	min-height: 100%;
}

.comment-page {
	display: flex;
	flex-direction: column;
	min-height: 100%;
}

/* 导航栏 */
.navbar {
	display: flex;
	justify-content: space-between;
	align-items: center;
	height: 44px;
	background-color: #ffffff;
	padding: 0 15px;
	border-bottom: 1px solid #eeeeee;
	position: fixed;
	top: 0;
	left: 0;
	right: 0;
	z-index: 100;
}

.back-btn {
	width: 44px;
	height: 44px;
	display: flex;
	align-items: center;
}

.back-btn .iconfont {
	font-size: 20px;
	color: #333333;
}

.title {
	font-size: 18px;
	color: #333333;
	font-weight: 500;
}

.empty-btn {
	width: 44px;
	height: 44px;
}

/* 订单信息提示 */
.order-info-tip {
	background-color: #ffffff;
	margin-top: 54px; /* 导航栏高度 + 10px */
	padding: 12px 15px;
	font-size: 14px;
	color: #666666;
}

/* 商品列表 */
.goods-list {
	background-color: #ffffff;
	margin-top: 10px;
}

/* 商品评价项 */
.goods-comment-item {
	padding: 15px;
}

/* 商品信息 */
.goods-info {
	display: flex;
	align-items: center;
}

.goods-img {
	width: 80px;
	height: 80px;
	border-radius: 8px;
	margin-right: 15px;
}

.goods-detail {
	flex: 1;
	overflow: hidden;
}

.goods-title {
	font-size: 16px;
	color: #333333;
	line-height: 1.4;
	display: -webkit-box;
	-webkit-line-clamp: 2;
	-webkit-box-orient: vertical;
	overflow: hidden;
}

.goods-attr {
	font-size: 14px;
	color: #666666;
	margin-top: 5px;
}

.goods-price {
	font-size: 16px;
	color: #ff4400;
	margin-top: 5px;
}

/* 评分区域 */
.rating-section {
	margin-top: 15px;
}

.section-title {
	font-size: 16px;
	color: #333333;
	margin-bottom: 10px;
}

.stars-container {
	display: flex;
	align-items: center;
}

.star-item {
	margin-right: 15px;
	cursor: pointer;
	transition: transform 0.2s;
}

.star-item:active {
	transform: scale(1.2);
}

.rating-text {
	margin-top: 5px;
	font-size: 14px;
	color: #666666;
}

/* 评价内容 */
.content-section {
	margin-top: 15px;
}

.comment-input {
	width: 100%;
	height: 120px;
	border: 1px solid #eeeeee;
	border-radius: 8px;
	padding: 10px;
	font-size: 14px;
	color: #333333;
	resize: none;
}

.word-count {
	text-align: right;
	font-size: 12px;
	color: #999999;
	margin-top: 5px;
}

/* 上传图片 */
.image-upload-section {
	margin-top: 15px;
}

.image-container {
	display: flex;
	flex-wrap: wrap;
}

.image-item {
	width: 70px;
	height: 70px;
	margin-right: 10px;
	margin-bottom: 10px;
	position: relative;
}

.image-item image {
	width: 100%;
	height: 100%;
	border-radius: 8px;
}

.delete-btn {
	position: absolute;
	top: -5px;
	right: -5px;
	width: 20px;
	height: 20px;
	background-color: rgba(0, 0, 0, 0.5);
	border-radius: 50%;
	display: flex;
	justify-content: center;
	align-items: center;
}

.delete-btn .iconfont {
	font-size: 12px;
	color: #ffffff;
}

.add-image-btn {
	width: 70px;
	height: 70px;
	border: 1px dashed #dddddd;
	border-radius: 8px;
	display: flex;
	justify-content: center;
	align-items: center;
	align-items: center;
}

.add-image-btn .iconfont {
	font-size: 24px;
	color: #999999;
}

/* 匿名评价 */
.anonymous-section {
	display: flex;
	align-items: center;
	justify-content: space-between;
	margin-top: 15px;
}

.anonymous-label {
	font-size: 16px;
	color: #333333;
}

.switch-container {
	transform: scale(0.8);
	transform-origin: right center;
}

/* 分隔线 */
.divider {
	height: 10px;
	background-color: #f5f5f5;
	margin-left: -15px;
	margin-right: -15px;
}

/* 提交按钮 */
.submit-btn {
	height: 50px;
	background-color: #007aff;
	color: #ffffff;
	font-size: 18px;
	display: flex;
	justify-content: center;
	align-items: center;
	border-radius: 8px;
	margin: 20px 15px;
}

.submit-btn.disabled {
	background-color: #99ccff;
}
</style>